# -*- coding: utf-8 -*-
# @Time    : 2023/5/9 0009 10:36
# @Author  : zcj
# @File    : Ding_send_linux.py
# @Software : PyCharm
import os
import time
import hmac
import hashlib
import base64
import urllib.parse
import json
import urllib3
from common.read_config import Docof
from report.send_linux.ssh_linux import send_linux

"""
此脚本是把测试报告地址（上传到linux的）发送到钉钉群里
如果是jenkins执行 下面需修改
"""


dc = Docof()
# 执行环境的url读取
secret_conf = dc.get_value_from_option("send_dingding", "secret")
url_webhook_conf = dc.get_value_from_option("send_dingding", "url_webhook")

timestamp = str(round(time.time() * 1000))
secret = secret_conf  # 加签
secret_enc = secret.encode('utf-8')
string_to_sign = '{}\n{}'.format(timestamp, secret)
string_to_sign_enc = string_to_sign.encode('utf-8')
hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))


def DingTalkSend(report_url):
    d = {}
    # 获取项目绝对路径
    path = os.path.abspath(os.path.dirname(__file__))
    # 打开prometheusData 获取需要发送的信息
    f = open(path + r'/allure-report/export/prometheusData.txt', 'r')
    for lines in f:
        for c in lines:
            launch_name = lines.strip('\n').split(' ')[0]
            num = lines.strip('\n').split(' ')[1]
            d.update({launch_name: num})
    print(d)
    f.close()
    retries_run = d.get('launch_retries_run')  # 运行总数
    print('运行总数:{}'.format(retries_run))
    status_passed = d.get('launch_status_passed')  # 通过数量
    print('通过数量：{}'.format(status_passed))
    status_failed = d.get('launch_status_failed')  # 不通过数量
    print('失败数量：{}'.format(status_failed))
    pass_re = "%.f%%" % (float(status_passed) / float(retries_run) * 100)
    print("通过率：{}".format(pass_re))

    # 钉钉推送
    url = f'{url_webhook_conf}&timestamp={timestamp}&sign={sign}'

    con = {"msgtype": "text",
           "text": {
               "content": "Pytest_Allure_Demo自动化脚本执行完成。"
                          "\n测试概述:"
                          "\n运行总数:" + retries_run +
                          "\n通过数量:" + status_passed +
                          "\n失败数量:" + status_failed +
                          "\n通过率:" + pass_re +
                          # "\n构建地址：\n" + job_url +
                          "\n报告地址：\n" + report_url  # linux的tomcat服务器的文件存放路径
           },
           "at": {
               "atMobiles": [
                   "130xxxxxxxx"  # 如果需要@某人，这里写他的手机号
               ],
               "isAtAll": 1  # 如果需要@所有人，这些写1
           }

           }
    try:
        urllib3.disable_warnings()
        http = urllib3.PoolManager()
        jd = json.dumps(con)
        jd = bytes(jd, 'utf-8')
        http.request('POST', url, body=jd, headers={'Content-Type': 'application/json'})
    except Exception as e:
        print(e)


if __name__ == '__main__':
    report = send_linux()  # 会返回inux的tomcat服务器的文件存放路径
    DingTalkSend(report)
